package com.braska.hewankurban;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.braska.hewankurban.db.Bobot_Penyakit;
import com.braska.hewankurban.db.DatabaseHandler;
import com.braska.hewankurban.db.Gejala;
import com.braska.hewankurban.db.Penyakit;
import com.braska.hewankurban.helper.CustomAdapter;
import com.braska.hewankurban.helper.ScrollViewHelper;
import com.braska.hewankurban.helper.ServiceHelper;
import android.R.raw;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PeriksaActivity extends Activity {

	public ListAdapter adapter;
	EditText jenishewan;
	ServiceHelper srv = new ServiceHelper();

	ArrayList<HashMap<String, String>> List;
	Intent ia;
	String jenis;
	ListView diagnosa;
	DatabaseHandler db = new DatabaseHandler(this);
	CheckBox r1, r2, r3, r4, r5, r6, r7;
	HashMap result;
	Double value;
	double maxval = 0;

	StringBuffer check = new StringBuffer();
	String umur = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_periksa);
		// jenishewan = (EditText) findViewById(R.id.jenis_hewan);
		LinearLayout gambar_1 = (LinearLayout) findViewById(R.id.gambar1);
		LinearLayout gambar_2 = (LinearLayout) findViewById(R.id.gambar2);
		LinearLayout gambar_3 = (LinearLayout) findViewById(R.id.gambar3);
		LinearLayout posisi1 = (LinearLayout) findViewById(R.id.posisi1);
		LinearLayout posisi2 = (LinearLayout) findViewById(R.id.posisi2);
		LinearLayout posisi3 = (LinearLayout) findViewById(R.id.posisi3);
		LinearLayout posisi4 = (LinearLayout) findViewById(R.id.posisi4);
		RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
		
		
		r1 = (CheckBox) findViewById(R.id.c_1);
		r2 = (CheckBox) findViewById(R.id.c_2);
		r3 = (CheckBox) findViewById(R.id.c_3);
		r4 = (CheckBox) findViewById(R.id.c_4);
		r5 = (CheckBox) findViewById(R.id.c_5);
		r6 = (CheckBox) findViewById(R.id.c_6);
		r7 = (CheckBox) findViewById(R.id.c_7);

		
		
		final RadioButton radio1 = (RadioButton) findViewById(R.id.radio1);
		final RadioButton radio2 = (RadioButton) findViewById(R.id.radio2);
		final RadioButton radio3 = (RadioButton) findViewById(R.id.radio3);

		final EditText berat = (EditText) findViewById(R.id.ed_berat);

		diagnosa = (ListView) findViewById(R.id.diagnosa);

		ia = new Intent(this, HasilActivity.class);
		Bundle extras = getIntent().getExtras();

		jenis = extras.getString("jenis");
		final String nama = extras.getString("nama");
		final String id_user = extras.getString("id");

		Button sumbit = (Button) findViewById(R.id.btn_submit);

		
		if (jenis.equals("2")) {
			// l_3.setVisibility(View.VISIBLE);
			posisi1.setBackgroundColor(Color.parseColor("#FC8F05"));
			posisi2.setBackgroundColor(Color.parseColor("#FC8F05"));
			posisi3.setBackgroundColor(Color.parseColor("#FC8F05"));
			posisi4.setBackgroundColor(Color.parseColor("#FC8F05"));
			sumbit.setBackgroundColor(Color.parseColor("#FC8F05"));
			gambar_3.setVisibility(View.VISIBLE);
			radio3.setVisibility(View.VISIBLE);
			gambar_1.setBackgroundResource(R.drawable.kambing_a);
			gambar_2.setBackgroundResource(R.drawable.kambing_b);
			gambar_3.setBackgroundResource(R.drawable.kambing_c);

			radio1.setText("<6 Bulan");
			radio2.setText("<1 Tahun");
			radio3.setText(">1 Tahun");

			Log.i("jenis", jenis);
		} else if (jenis.equals("1")) {
			gambar_3.setVisibility(View.VISIBLE);
			radio3.setVisibility(View.VISIBLE);
			posisi1.setBackgroundColor(Color.parseColor("#18B7C5"));
			posisi2.setBackgroundColor(Color.parseColor("#18B7C5"));
			posisi3.setBackgroundColor(Color.parseColor("#18B7C5"));
			posisi4.setBackgroundColor(Color.parseColor("#18B7C5"));
			sumbit.setBackgroundColor(Color.parseColor("#18B7C5"));
			gambar_1.setBackgroundResource(R.drawable.sapi_a);
			gambar_2.setBackgroundResource(R.drawable.sapi_b);
			gambar_3.setBackgroundResource(R.drawable.sapi_c);
			
			radio1.setText("<1 Tahun");
			radio2.setText(">1 Tahun");
			radio3.setText(">2 Tahun");

		} else {
			gambar_3.setVisibility(View.INVISIBLE);
			radio3.setVisibility(View.INVISIBLE);
			posisi1.setBackgroundColor(Color.parseColor("#54D34F"));
			posisi2.setBackgroundColor(Color.parseColor("#54D34F"));
			posisi3.setBackgroundColor(Color.parseColor("#54D34F"));
			posisi4.setBackgroundColor(Color.parseColor("#54D34F"));
			sumbit.setBackgroundColor(Color.parseColor("#54D34F"));
			gambar_1.setBackgroundResource(R.drawable.domba_a);
			gambar_2.setBackgroundResource(R.drawable.domba_b);
			
			radio1.setText("<6 Bulan");
			radio2.setText(">6 Bulan");
			
		}
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.radio1:
					umur = radio1.getText().toString();
					break;
				case R.id.radio2:
					umur = radio2.getText().toString();
					break;
				case R.id.radio3:
					umur = radio3.getText().toString();
					break;
				}
			}
		});


		r1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r1.isChecked()) {
					check.append(r1.getText()+",");
					
					r7.setEnabled(false);
					//ia.putExtra("cacatfisik", r1.getText().toString());
					System.out.println("Checked");
					System.out.println(r1.getText()+",");
				} else {
					
					r7.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});

		r2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r2.isChecked()) {
					check.append(r2.getText()+",");
					r7.setEnabled(false);
					//ia.putExtra("cacatfisik", r2.getText().toString());
					System.out.println("Checked");
				} else {
					
					r7.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});

		r3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r3.isChecked()) {
					check.append(r3.getText()+",");
					r7.setEnabled(false);
					System.out.println("Checked");
				} else {
					r7.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});

		r4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r4.isChecked()) {
					check.append(r4.getText()+",");
					r7.setEnabled(false);
					System.out.println("Checked");
				} else {
					r7.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});

		r5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r5.isChecked()) {
					check.append(r5.getText()+",");
					r7.setEnabled(false);
					System.out.println("Checked");
				} else {
					r7.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});

		r6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r6.isChecked()) {
					check.append(r6.getText()+",");
					r7.setEnabled(false);
					System.out.println("Checked");
				} else {
					r7.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});

		r7.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (r7.isChecked()) {
					check.append(r7.getText()+",");
					r1.setEnabled(false);
					r2.setEnabled(false);
					r3.setEnabled(false);
					r4.setEnabled(false);
					r5.setEnabled(false);
					r6.setEnabled(false);
					System.out.println("Checked");
				} else {
					r1.setEnabled(true);
					r2.setEnabled(true);
					r3.setEnabled(true);
					r4.setEnabled(true);
					r5.setEnabled(true);
					r6.setEnabled(true);
					System.out.println("unChecked");
				}

			}
		});
		
		
		sumbit.setOnClickListener(new OnClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				clicksubmit();
				ia.putExtra("key1", umur);
				
				ia.putExtra("berat", berat.getText().toString());
				ia.putExtra("jenishewan", jenis);
				ia.putExtra("id", id_user);
				ia.putExtra("maxval", maxval);
				ia.putExtra("nama", nama);
				ia.putExtra("check", check+"");
				
				
				if (berat.getText().toString().trim().equals("")) {
					Toast.makeText(getBaseContext(), "Berat harus di isi", Toast.LENGTH_LONG)
					.show();
					return;
				}
				if (check.toString().trim().equals("")) {
					Toast.makeText(getBaseContext(), "Cacat harus di isi", Toast.LENGTH_LONG)
					.show();
					return;
				}
				if (umur.toString().trim().equals("")) {
					Toast.makeText(getBaseContext(), "umur harus di isi", Toast.LENGTH_LONG)
					.show();
					return;
				}

				
				
				startActivity(ia);
				finish();

			}
		});


		new gejalaTask().execute();
		// new penyakitTask().execute();
	}
	
	
	
	
	

	private class gejalaTask extends AsyncTask<String, Void, JSONArray> {
		private ProgressDialog dialog = new ProgressDialog(PeriksaActivity.this);

		protected void onPreExecute() {
			dialog.setMessage("Loading....");
			dialog.show();

		}

		@Override
		protected JSONArray doInBackground(String... params) {
			// TODO Auto-generated method stub
			JSONArray in = null;
			String srvres = null;
			try {

				srvres = srv.gejala();

				try {
					JSONArray ja = new JSONArray("[" + srvres + "]");
					JSONArray innerJSONArray = ja.getJSONArray(0);
					JSONObject json = innerJSONArray.getJSONObject(0);
					Log.d("anunedowoooobangettttt", innerJSONArray.length()
							+ "");
					in = innerJSONArray;
					Gejala g = new Gejala();
					db.deletgejala();
					for (int i = 0; i < in.length(); i++) {
						JSONObject j = innerJSONArray.getJSONObject(i);

						g.setId_gejala(j.getInt("id_gejala"));
						g.setKd_gejala(j.getString("kd_gejala"));
						g.setGejala(j.getString("gejala"));
						db.tambahgejala(g);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return in;
		}

		@Override
		protected void onPostExecute(JSONArray result) {
			// TODO Auto-generated method stub

			// List = new ArrayList<HashMap<String, String>>();
			ArrayList<HashMap<String, Object>> postitem = new ArrayList<HashMap<String, Object>>();
			for (int i = 0; i < result.length(); i++) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				JSONObject j;
				try {
					j = result.getJSONObject(i);
					map.put("id", j.getString("id_gejala").toString());
					map.put("pilihan", j.getString("gejala").toString());
					// map.put("bobot", j.getString("bobot").toString());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					// Toast.makeText(getApplicationContext(),
					// "Koneksi tidak di Temukan", Toast.LENGTH_LONG).show();
					// Log.d("test", e + "");
				}

				postitem.add(map);

			}
			adapter = new CustomAdapter(getApplicationContext(), postitem,
					R.layout.activity_periksa_list, new String[] { "id",
							"pilihan" }, new int[] { R.id.id, R.id.pertanyaan });

			diagnosa.setAdapter(adapter);
			ScrollViewHelper.getListViewSize(diagnosa);
			new penyakitTask().execute();
			dialog.dismiss();
		}

	}

	private class penyakitTask extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog = new ProgressDialog(PeriksaActivity.this);

		protected void onPreExecute() {
			dialog.setMessage("Loading....");
			dialog.show();

		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			// new bobotpenyakitTask().execute();
			dialog.dismiss();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {
				Penyakit p = new Penyakit();
				Bobot_Penyakit b = new Bobot_Penyakit();
				String srvres = srv.allpenyakit();
				String srvres1 = srv.getbobotgejala();
				Log.i("alakazam", srvres);
				try {
					JSONArray ja = new JSONArray("[" + srvres + "]");
					JSONArray innerJSONArray = ja.getJSONArray(0);
					JSONObject json = innerJSONArray.getJSONObject(0);
					Log.d("anunedowoooobangettttt", innerJSONArray.length()
							+ "");
					db.deletpenyakit();

					for (int i = 0; i < innerJSONArray.length(); i++) {

						JSONObject j = innerJSONArray.getJSONObject(i);
						p.setId_penyakit(j.getInt("id_penyakit"));
						p.setKd_penyakit(j.getString("kd_penyakit"));
						p.setPenyakit(j.getString("penyakit"));
						db.tambahpenyakit(p);

					}

				} catch (Exception e) {
					// TODO: handle exception
				}

				try {
					JSONArray ja = new JSONArray("[" + srvres1 + "]");
					JSONArray innerJSONArray = ja.getJSONArray(0);
					JSONObject json = innerJSONArray.getJSONObject(0);
					Log.d("anunedowoooobangettttt", innerJSONArray.length()
							+ "");
					db.deletebobotpenyakit();

					for (int i = 0; i < innerJSONArray.length(); i++) {

						JSONObject j = innerJSONArray.getJSONObject(i);
						b.setId_bobotpenyakit(j.getInt("id_bobot_gejala"));
						b.setId_penyakit(j.getInt("id_penyakit"));
						b.setId_gejala(j.getInt("id_gejala"));
						b.setBobot(j.getDouble("bobot"));
						b.setJenishewan(j.getString("jenishewan"));
						db.tambahbobotgejala(b);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
			return true;
		}

	}

	private class bobotpenyakitTask extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog = new ProgressDialog(PeriksaActivity.this);

		protected void onPreExecute() {
			dialog.setMessage("Loading....");
			dialog.show();

		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			dialog.dismiss();

		}

		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {
				Bobot_Penyakit b = new Bobot_Penyakit();
				String srvres = srv.getbobotgejala();
				Log.i("alakazam", srvres);
				try {
					JSONArray ja = new JSONArray("[" + srvres + "]");
					JSONArray innerJSONArray = ja.getJSONArray(0);
					JSONObject json = innerJSONArray.getJSONObject(0);
					Log.d("anunedowoooobangettttt", innerJSONArray.length()
							+ "");
					db.deletebobotpenyakit();

					for (int i = 0; i < innerJSONArray.length(); i++) {

						JSONObject j = innerJSONArray.getJSONObject(i);
						b.setId_bobotpenyakit(j.getInt("id_bobot_gejala"));
						b.setId_penyakit(j.getInt("id_penyakit"));
						b.setId_gejala(j.getInt("id_gejala"));
						b.setBobot(j.getDouble("bobot"));
						b.setJenishewan(j.getString("jenishewan"));
						db.tambahbobotgejala(b);
					}

				} catch (Exception e) {
					// TODO: handle exception
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
			return true;
		}

	}

	public void clicksubmit() {
		List<Integer> lst = new ArrayList<Integer>();
		lst.clear();
		String a = "";
		String b = "";

		for (int i = 0; i < diagnosa.getCount(); i++) {
			View v = getViewByPosition(i, diagnosa);
			TextView tv = (TextView) v.findViewById(R.id.id);
			CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
			if (cb.isChecked()) {
				// a = a + " " + tv.getText();
				lst.add(Integer.parseInt(tv.getText().toString()));
			}

		}

		result = new HashMap();
		result = db.getpenyakit_from_diagnosis(lst, jenis);
		Log.i("result perhitungan", result + "");
		Toast.makeText(this, "checked : " + lst.toString(), Toast.LENGTH_LONG)
				.show();
		ia.putExtra("id", a);

		Iterator myVeryOwnIterator = result.keySet().iterator();
		while (myVeryOwnIterator.hasNext()) {
			String key = (String) myVeryOwnIterator.next();
			value = (Double) result.get(key);
			Log.i("key", key);
			Log.i("val", value + "");
			if (value >= maxval) {
				maxval = value;
			}

		}

		Log.i("maxval", maxval + "");

	}

	public View getViewByPosition(int position, ListView listView) {
		final int firstListItemPosition = listView.getFirstVisiblePosition();
		final int lastListItemPosition = firstListItemPosition
				+ listView.getChildCount() - 1;

		if (position < firstListItemPosition || position > lastListItemPosition) {
			return listView.getAdapter().getView(position,
					listView.getChildAt(position), listView);
		} else {
			final int childIndex = position - firstListItemPosition;
			return listView.getChildAt(childIndex);
		}
	}

}
